<?php

declare(strict_types=1);

namespace App\Service;

use App\Constants\XZXResponseCode;
use App\Exception\XZXValidationException;
use App\Model\Dao\CommissionSalesDao;
use App\Model\Dao\TradeOrderDetailDao;
use App\Model\Dao\StatDailyTradeDao;
use App\Model\Dao\MchConfigDao;
use App\Model\Dao\MchInfoDao;
use App\Utils\CustomUtils;
use App\Utils\NumberUtils;
use App\Utils\RedisUtils;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\Arr;


/**
 * Class DashboardService
 *
 * @package App\Service
 */
class DashboardService {

    /**
     * @Inject()
     * @var MchConfigDao
     */
    private $MchConfigDao;

    /**
     * @Inject()
     * @var CommissionSalesDao
     */
    private $CommissionSalesDao;

    /**
     * @Inject()
     * @var StatDailyTradeDao
     */
    private $StatDailyTradeDao;


    /**
     * @Inject()
     * @var TradeOrderDetailDao
     */
    private $TradeOrderDetailDao;

    /**
     * 平台销售看板数据
     *
     * @param $param
     *
     * @return array
     */
    public function platformStatSales ($param) {

        $adminId   = $param['adminId'];
        $mchIdList = $param['mchIdList'];

        $data = [
            'isSale'            => true,
            'daySuccessCount'   => 0,
            'monthSuccessCount' => 0,
            'amountList'        => [// 'currency' => ['day' => 0, 'month' => 0, 'balance' => 0],
            ],
        ];

        // 商户ID列表为空,没啥好统计的直接返回
        if (empty($mchIdList)) {
            return CustomUtils::buildSuccess($data);
        }

        $rangeDay = [
            Carbon::now()->setTime(0, 0, 0)->getTimestamp(),
            Carbon::now()->setTime(23, 59, 59)->getTimestamp(),
        ];

        $rangeMonth = [
            Carbon::now()->firstOfMonth()->setTime(0, 0, 0)->getTimestamp(),
            Carbon::now()->lastOfMonth()->setTime(23, 59, 59)->getTimestamp(),
        ];

        $data['daySuccessCount'] = $this->TradeOrderDetailDao->getWhereCount(function (Builder $query) use ($rangeDay, $mchIdList) {
            $query->whereBetween('settleTime', $rangeDay);
            $query->where('isSettle', 2);
            $query->where('transStatus', 6);
            $query->whereIn('mchId', $mchIdList);
        });

        $data['monthSuccessCount'] = $this->TradeOrderDetailDao->getWhereCount(function (Builder $query) use ($rangeMonth, $mchIdList) {
            $query->whereBetween('settleTime', $rangeMonth);
            $query->where('isSettle', 2);
            $query->where('transStatus', 6);
            $query->whereIn('mchId', $mchIdList);
        });

        $dayList = $this->TradeOrderDetailDao->getSalesAmountList([
            'settleTimeRange' => $rangeDay,
            'mchIdList'       => $mchIdList,
        ]);

        $monthList = $this->TradeOrderDetailDao->getSalesAmountList([
            'settleTimeRange' => $rangeMonth,
            'mchIdList'       => $mchIdList,
        ]);

        $balanceList = $this->CommissionSalesDao->getSalesBalanceList(['salesId' => $adminId]);

        $dayList     = array_column($dayList, 'amount', 'currency');
        $monthList   = array_column($monthList, 'amount', 'currency');
        $balanceList = array_column($balanceList, 'amount', 'currency');

        $currencyList = array_unique(array_merge(array_keys($dayList), array_keys($monthList), array_keys($balanceList)));
        sort($currencyList);

        $amountList = [];
        foreach ($currencyList as $currency) {
            if ($currency) {
                array_push($amountList, [
                    'currency' => $currency,
                    'day'      => (int) Arr::get($dayList, $currency, 0),
                    'month'    => (int) Arr::get($monthList, $currency, 0),
                    'balance'  => (int) Arr::get($balanceList, $currency, 0),
                ]);
            }
        }

        $data['amountList'] = $amountList;

        return CustomUtils::buildSuccess($data);
    }

    public function lineChart ($param) {
        // $param = Arr::only($param, ['isBoc', 'code', 'name']);
        $list = $this->StatDailyTradeDao->getList($param);
        if ($param['lineType'] == 1) {
            $list = array_map(function ($item) {
                return Arr::only($item, ['statDate', 'successCount']);
            }, $list);
        }

        if ($param['lineType'] == 2) {
            $list = array_map(function ($item) {
                return Arr::only($item, ['statDate', 'successSettleAmount']);
            }, $list);
        }


        $data = [
            // 'total' => $total,
            'list' => $list,
        ];

        return CustomUtils::buildSuccess($data);
    }

    public function realTimeStats ($param) {
        $data                                  = [];
        $data['dailyTradeSuccessCount']        = $this->TradeOrderDetailDao->getWhereCount(function (Builder $query) use ($param) {
            $query->where('transStatus', 6);
            $query->where('mchId', $param['mchId']);
            $query->whereBetween('createTime', $param['dailyStatsCreateTimeRange']);
        });
        $data['dailyTradeFailedCount']         = $this->TradeOrderDetailDao->getWhereCount(function (Builder $query) use ($param) {
            $query->where('transStatus', 5);
            $query->where('mchId', $param['mchId']);
            $query->whereBetween('createTime', $param['dailyStatsCreateTimeRange']);
        });
        $data['dailyTradeSuccessSettleAmount'] = $this->TradeOrderDetailDao->getWhereSum(function (Builder $query) use ($param) {
            $query->where('transStatus', 6);
            $query->where('isSettle', 2);
            $query->where('mchId', $param['mchId']);
            $query->whereBetween('createTime', $param['dailyStatsCreateTimeRange']);
        }, 'settleAmount');

        $data['monthlyTradeSuccessCount'] = $this->TradeOrderDetailDao->getWhereCount(function (Builder $query) use ($param) {
            $query->where('transStatus', 6);
            $query->where('mchId', $param['mchId']);
            $query->whereBetween('createTime', $param['monthlyStatsCreateTimeRange']);
        });

        $data['monthlyTradeFailedCount'] = $this->TradeOrderDetailDao->getWhereCount(function (Builder $query) use ($param) {
            $query->where('transStatus', 5);
            $query->where('mchId', $param['mchId']);
            $query->whereBetween('createTime', $param['monthlyStatsCreateTimeRange']);
        });


        $data['monthlyTradeSuccessSettleAmount'] = $this->TradeOrderDetailDao->getWhereSum(function (Builder $query) use ($param) {
            $query->where('transStatus', 6);
            $query->where('isSettle', 2);
            $query->where('mchId', $param['mchId']);
            $query->whereBetween('createTime', $param['monthlyStatsCreateTimeRange']);
        }, 'settleAmount');

        $data['settleCurrency'] = '';
        $mchConfigInfo          = $this->MchConfigDao->getWhere(['mchId' => $param['mchId']]);
        if (!$mchConfigInfo) {
            $data['settleCurrency'] = '-';
        }
        $data['settleCurrency'] = $mchConfigInfo['settleCurrency'];
        // $data = array(
        //     'total' => $total,
        //     'list' => $list
        // );

        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE, XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), $data);

    }

}
